//
//  EditUserInfoViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/5/26.
//

#import "EditUserInfoViewController.h"
#import "UITextView+Placeholder.h"
#import "ChooseBottomAlertView.h"
#import "EditUserInfoManager.h"
#import "FileUploadManager.h"
#import "GetUserInfoManager.h"


@interface EditUserInfoViewController ()<UITextFieldDelegate,JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)UIImageView *headImageView;
@property(nonatomic,strong)UIView *bgView;
@property(nonatomic,strong)UITextField *nameTF;
@property(nonatomic,strong)UILabel *countLabel;
@property(nonatomic,strong)UILabel *sexLabel;
@property(nonatomic,strong)UITextView *textView;
@property(nonatomic,strong)ChooseBottomAlertView *chooseView;
@property(nonatomic,assign)NSInteger sex_index;
@property(nonatomic,copy)NSArray *sexArr;
@property(nonatomic,strong)EditUserInfoManager *editManager;
@property(nonatomic,strong)FileUploadManager *uploadManager;
@property(nonatomic,strong)JPProgressHUD *hud;
@property(nonatomic,strong)UIImage *sendImage;
@property(nonatomic,strong)NSString *picUrl;
@property(nonatomic,strong)GetUserInfoManager *userInfoManager;

@end

@implementation EditUserInfoViewController

-(EditUserInfoManager *)editManager{
    if(!_editManager){
        _editManager = [[EditUserInfoManager alloc]init];
        _editManager.delegate = self;
    }
    return _editManager;
}

-(FileUploadManager *)uploadManager{
    if(!_uploadManager){
        _uploadManager = [[FileUploadManager alloc]init];
        _uploadManager.delegate = self;
    }
    return _uploadManager;
}

-(GetUserInfoManager *)userInfoManager{
    if(!_userInfoManager){
        _userInfoManager = [[GetUserInfoManager alloc]init];
        _userInfoManager.delegate = self;
    }
    return _userInfoManager;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    
    if(self.userModel.sex&&[self.userModel.sex isEqualToString:@"2"]){
        self.sex_index = 1;
    }else if(self.userModel.sex&&[self.userModel.sex isEqualToString:@"1"]){
        self.sex_index = 0;
    }else{
        self.sex_index = 2;
    }
    self.sexArr = @[@"男",@"女",@"其他"];
    [self createUI];
    [self getUserInfo];
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 获取当前可用宽度并更新布局
        self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
        self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
        self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
        if(self.chooseView&&self.chooseView.isShow == YES){
            self.chooseView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight);
            self.chooseView.currentAvailableWidth = self.currentAvailableWidth;
            self.chooseView.currentAvailableHeight = self.currentAvailableHeight;
            [self.chooseView refreshWidth];
        }else{
            if(self.chooseView){
                self.chooseView = nil;
            }
        }
            
        });
    }
}

#pragma mark - 获取个人信息
-(void)getUserInfo{
    
    self.userInfoManager.userId = self.userModel.userId;
    [self.userInfoManager loadData];
    
}


#pragma mark - 创建界面
-(void)createUI{
    
    [self.customNavigationBar setTitle:@"编辑个人资料"];
    UIButton *saveBtn = [[UIButton alloc]init];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setTitleColor:KThemeColor forState:UIControlStateNormal];
    saveBtn.titleLabel.font = JPUIFontPingFangSCMedium(16);
    [saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
    saveBtn.ym_acceptEventInterval = 2.0;
    [self.customNavigationBar addSubview:saveBtn];
    CGFloat s_w = [self getStringWidthWithText:saveBtn.titleLabel.text font:saveBtn.titleLabel.font viewHeight:40];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(@-6);
        make.width.mas_equalTo(s_w+20);
        make.height.mas_equalTo(@40);
        make.bottom.mas_equalTo(@-2);
    }];
    
    __weak typeof(self)self_weak_ = self;
    self.headImageView = [[UIImageView alloc]init];
    CGFloat head_w = [DeviceUtils getAdaptedWidthForDesignWidth:80 andCurrentAvailableWidth:self.currentAvailableWidth];
    self.headImageView.layer.cornerRadius = head_w/2.0;
    self.headImageView.layer.masksToBounds = YES;
    if(self.userModel.avatar){
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:self.userModel.avatar] placeholderImage:[UIImage imageNamed:@"mine_head_default"]];
    }else{
        self.headImageView.image = [UIImage imageNamed:@"mine_head_default"];
    }
    self.headImageView.layer.borderWidth = 3.0;
    self.headImageView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.headImageView.userInteractionEnabled = YES;
    [self.view addSubview:self.headImageView];
    [self.headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(head_w);
        make.centerX.mas_equalTo(self_weak_.view);
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+40);
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
        [self_weak_ choosePhoto];
    }];
    [self.headImageView addGestureRecognizer:tap];
    
    CGFloat camera_w = [DeviceUtils getAdaptedWidthForDesignWidth:28 andCurrentAvailableWidth:self.currentAvailableWidth];
    UIButton *cameraBtn = [[UIButton alloc]init];
    [cameraBtn setImage:[UIImage imageNamed:@"mine_userinfo_camera"] forState:UIControlStateNormal];
    cameraBtn.backgroundColor = UIColorHex(0xCCCCCC);
    cameraBtn.layer.cornerRadius = camera_w/2.0;
    cameraBtn.layer.masksToBounds = YES;
    cameraBtn.layer.borderWidth = 3.0;
    cameraBtn.layer.borderColor = KbgColor.CGColor;
    cameraBtn.adjustsImageWhenHighlighted = NO;
    [cameraBtn addTarget:self action:@selector(cameraBtnCick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cameraBtn];
    [cameraBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self_weak_.headImageView.mas_right);
        make.bottom.mas_equalTo(self_weak_.headImageView.mas_bottom);
        make.width.height.mas_equalTo(camera_w);
    }];
    
    self.bgView = [[UIView alloc]init];
    self.bgView.backgroundColor = [UIColor whiteColor];
    self.bgView.layer.cornerRadius = 10;
    self.bgView.layer.masksToBounds = YES;
    [self.view addSubview:self.bgView];
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self_weak_.headImageView.mas_bottom).offset(40);
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        if(isIPAD){
            make.height.mas_equalTo(@198);
        }else{
            make.height.mas_equalTo(kWFit(198));
        }
    }];
    
    NSArray *arr = @[@"昵称",@"性别",@"签名"];
    for(NSInteger i = 0;i < arr.count;i++){
        UIView *bView = [[UIView alloc]init];
        [self.bgView addSubview:bView];
        [bView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(@0);
            if(isIPAD){
                if(i < 2){
                    make.height.mas_equalTo(53);
                }else{
                    make.height.mas_equalTo(72);
                }
                make.top.mas_equalTo(i*63);
            }else{
                if(i < 2){
                    make.height.mas_equalTo(kWFit(53));
                }else{
                    make.height.mas_equalTo(kWFit(72));
                }
                make.top.mas_equalTo(i*kWFit(63));
            }
        }];
        if(i == 1){
            UITapGestureRecognizer *sextap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
                [self_weak_ showChooseView];
            }];
            [bView addGestureRecognizer:sextap];
        }
        UILabel *leftLabel = [[UILabel alloc]init];
        leftLabel.font = JPUIFontPingFangSCMedium(15);
        leftLabel.textColor = KFontBlackColor;
        leftLabel.userInteractionEnabled = YES;
        leftLabel.text = arr[i];
        [bView addSubview:leftLabel];
        [leftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(@16);
            if(isIPAD){
                make.height.mas_equalTo(21);
                make.top.mas_equalTo(16);
            }else{
                make.height.mas_equalTo(kWFit(21));
                make.top.mas_equalTo(kWFit(16));
            }
        }];
        if(i == 0){
            self.nameTF = [[UITextField alloc]init];
            self.nameTF.font = JPUIFontPingFangSCRegular(14);
            self.nameTF.textColor = KFontGrayColor;
            self.nameTF.borderStyle = UITextBorderStyleNone;
            self.nameTF.keyboardType = UIKeyboardTypeDefault;
            self.nameTF.tintColor = KThemeColor;
            self.nameTF.delegate = self;
            if(self.userModel.nickname){
                self.nameTF.text = self.userModel.nickname;
            }
            [bView addSubview:self.nameTF];
            [self.nameTF mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(@76);
                make.right.mas_equalTo(@-66);
                make.height.mas_equalTo(@35);
                make.centerY.mas_equalTo(bView);
            }];
            self.countLabel = [[UILabel alloc]init];
            self.countLabel.textColor = UIColorHex(0xCCCCCC);
            self.countLabel.textAlignment = NSTextAlignmentRight;
            self.countLabel.font = JPUIFontPingFangSCRegular(14);
            self.countLabel.text = [NSString stringWithFormat:@"%ld/16",self.nameTF.text.length];
            [bView addSubview:self.countLabel];
            [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(@-16);
                make.width.mas_equalTo(@45);
                make.height.mas_equalTo(@21);
                make.centerY.mas_equalTo(bView);
            }];
        }else if (i == 1){
            self.sexLabel = [[UILabel alloc]init];
            self.sexLabel.font = JPUIFontPingFangSCRegular(14);
            self.sexLabel.textColor = KFontGrayColor;
            self.sexLabel.userInteractionEnabled = YES;
            if(self.userModel.sex&&[self.userModel.sex isEqualToString:@"2"]){
                self.sexLabel.text = @"女";
            }else if (self.userModel.sex&&[self.userModel.sex isEqualToString:@"1"]){
                self.sexLabel.text = @"男";
            }else{
                self.sexLabel.text = @"其他";
            }
            [bView addSubview:self.sexLabel];
            [self.sexLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(@76);
                make.right.mas_equalTo(@-66);
                make.height.mas_equalTo(@21);
                make.centerY.mas_equalTo(bView);
            }];
            UIImageView *arrowImageView = [[UIImageView alloc]init];
            arrowImageView.image = [UIImage imageNamed:@"mine_right_arrow"];
            arrowImageView.userInteractionEnabled = YES;
            [bView addSubview:arrowImageView];
            [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(@-12);
                make.width.height.mas_equalTo(@16);
                make.centerY.mas_equalTo(bView);
            }];
        }else if (i == 2){
            self.textView = [[UITextView alloc]init];
            self.textView.backgroundColor = [UIColor whiteColor];
            self.textView.font = JPUIFontPingFangSCRegular(14);
            self.textView.textColor = KFontGrayColor;
            self.textView.tintColor = KThemeColor;
            [self.textView setPlaceholder:@"快设置你的日语岛签名吧！" placeholdColor:KFontGrayColor];
            self.textView.contentInset = UIEdgeInsetsZero;
            self.textView.textContainerInset = UIEdgeInsetsZero;
            if(self.userModel.introduction){
                self.textView.text = self.userModel.introduction;
            }
            [bView addSubview:self.textView];
            [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(@73);
                make.right.mas_equalTo(@-13);
                if(isIPAD){
                    make.top.mas_equalTo(@17);
                    make.bottom.mas_equalTo(-16);
                }else{
                    make.top.mas_equalTo(kWFit(17));
                    make.bottom.mas_equalTo(-kWFit(16));
                }
            }];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChangeText:) name:UITextViewTextDidChangeNotification object:self.textView];
        }
        
    }
}

#pragma mark - 刷新界面
-(void)refreshUI{
    if(self.userModel.avatar){
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:self.userModel.avatar] placeholderImage:[UIImage imageNamed:@"mine_head_default"]];
    }else{
        self.headImageView.image = [UIImage imageNamed:@"mine_head_default"];
    }
    if(self.userModel.sex&&[self.userModel.sex isEqualToString:@"2"]){
        self.sex_index = 1;
    }else if (self.userModel.sex&&[self.userModel.sex isEqualToString:@"1"]){
        self.sex_index = 0;
    }else{
        self.sex_index = 2;
    }
    if(self.userModel.nickname){
        self.nameTF.text = self.userModel.nickname;
    }
    self.countLabel.text = [NSString stringWithFormat:@"%ld/16",self.nameTF.text.length];
    if(self.userModel.sex&&[self.userModel.sex isEqualToString:@"2"]){
        self.sexLabel.text = @"女";
    }else if (self.userModel.sex&&[self.userModel.sex isEqualToString:@"1"]){
        self.sexLabel.text = @"男";
    }else{
        self.sexLabel.text = @"其他";
    }
    if(self.userModel.introduction){
        self.textView.text = self.userModel.introduction;
    }
}

#pragma mark - 性别选择
-(void)showChooseView{
    [self.nameTF resignFirstResponder];
    [self.textView resignFirstResponder];
    if(!self.chooseView){
        self.chooseView = [[ChooseBottomAlertView alloc]initWithFrame:CGRectMake(0, 0,self.currentAvailableWidth, self.currentAvailableHeight) andTitleArr:self.sexArr];
    }
    self.chooseView.currentAvailableWidth = self.currentAvailableWidth;
    self.chooseView.currentAvailableHeight = self.currentAvailableHeight;
    self.chooseView.titleArr = self.sexArr;
    self.chooseView.sel_index = self.sex_index;
    UIWindow *keyWindow = KEY_WINDOW;
    if(keyWindow){
        [keyWindow addSubview:self.chooseView];
    }
    [self.chooseView show];
    __weak typeof(self)self_weak_  = self;
    [self.chooseView setSureBlock:^(NSInteger index) {
        [self_weak_.chooseView hidden];
        self_weak_.sex_index = index;
        self_weak_.sexLabel.text = self_weak_.sexArr[index];
    }];
}

#pragma mark - 监测用户输入文本长度
- (void)textViewDidChangeText:(NSNotification *)notification{

   //最大输入长度,中英文字符都按一个字符计算
    static int kMaxLength = 20;
    UITextView *textView = (UITextView *)notification.object;
    NSString *toBeString = textView.text;
     // 获取键盘输入模式
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage];
    // 中文输入的时候,可能有markedText(高亮选择的文字),需要判断这种状态
    // zh-Hans表示简体中文输入, 包括简体拼音，健体五笔，简体手写
    if ([lang isEqualToString:@"zh-Hans"]) {
        UITextRange *selectedRange = [textView markedTextRange];
        //获取高亮选择部分
        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，表明输入结束,则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > kMaxLength) {
                // 截取子串
                textView.text = [toBeString substringToIndex:kMaxLength];
            }
        }

    } else {
        // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        if (toBeString.length > kMaxLength) {
            // 截取子串
            textView.text = [toBeString substringToIndex:kMaxLength];
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // 获取当前文本框的最新文本
    NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    // 更新字符数量显示
    self.countLabel.text = [NSString stringWithFormat:@"%ld/16", newText.length>16?16:newText.length];
    // 检查文本长度是否超过限制
    if (newText.length > 16) {
        return NO; // 返回 NO 以阻止超过限制长度的输入
    }
    return YES; // 允许输入
}

#pragma mark - 保存
-(void)saveBtnClick{
    
    if(self.sendImage){
        //如果有换头像 先上传头像
        [self uploadWithImage:self.sendImage];
    }else{
        [self save];
    }
    
}

-(void)save{
    
    self.editManager.userId = self.userModel.userId;
    //头像
    if(self.picUrl){
        self.editManager.avatar = self.picUrl;
    }
    //昵称
    if(self.userModel.nickname){
        if(self.nameTF.text.length > 0){
            if(![self.userModel.nickname isEqualToString:self.nameTF.text]){
                self.editManager.nickname = self.nameTF.text;
            }
        }
    }else{
        if(self.nameTF.text.length > 0){
            self.editManager.nickname = self.nameTF.text;
        }
    }
    //性别
    if(self.userModel.sex){
        if(self.userModel.sex.integerValue != self.sex_index+1){
            self.editManager.sex = [NSString stringWithFormat:@"%ld",self.sex_index+1];
        }
    }else{
        self.editManager.sex = [NSString stringWithFormat:@"%ld",self.sex_index+1];
    }
    //简介
    if(self.userModel.introduction){
         if(![self.userModel.introduction isEqualToString:self.textView.text]){
             self.editManager.introduction = self.textView.text;
         }
    }else{
        self.editManager.introduction = self.textView.text;
    }
    if((!self.editManager.avatar)&&(!self.editManager.nickname)&&(!self.editManager.sex)&&(!self.editManager.introduction)){
        [JPProgressHUD showMsg:@"没有任何修改"];
        return;
    }
    [self.editManager loadData];
}

#pragma mark - 相机
-(void)cameraBtnCick{
    [self choosePhoto];
}

#pragma mark - 头像选择
-(void)choosePhoto{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted||status == PHAuthorizationStatusDenied){
         //无权限
        [JPProgressHUD showMsg:@"无权限访问相册，请去设置页面打开访问权限"];
         return ;
    }else if (status == PHAuthorizationStatusNotDetermined){
         //第一次进来还没有选择是否授权
         [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
             dispatch_async(dispatch_get_main_queue(), ^{
                 if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied){
                     // 用户拒绝，跳转到自定义提示页面
                     [JPProgressHUD showMsg:@"无权限访问相册，请去设置页面打开访问权限"];
                 }else if (status == PHAuthorizationStatusAuthorized){
                     // 用户授权，弹出相册对话框
                     [self addpic];
                 }
             });
         }];
         return;
    }else{
        // 用户授权，弹出相册对话框
        [self addpic];
    }
}

-(void)addpic{
    
    ZLPhotoPreviewSheet *ac = [[ZLPhotoPreviewSheet alloc]initWithSelectedAssets:nil];
    ZLPhotoConfiguration *config = [ZLPhotoConfiguration default];
    config.allowSelectVideo = NO;
    config.allowSelectGif = NO;
    config.maxSelectCount = 1;
    //让相册点击直接出现裁剪页面
    [config.editImageConfiguration setClipRatios:@[[ZLImageClipRatio wh1x1]]];
    config.editAfterSelectThumbnailImage = YES;
//    config.showClipDirectlyIfOnlyHasClipTool = YES;
    [config.editImageConfiguration setTools_objc:@[@(EditToolClip)]];
    __weak typeof(self)self_weak_ = self;
    ac.selectImageBlock = ^(NSArray<ZLPhotoModel *> *results, BOOL isOriginal) {
         NSArray *photos = [results valueForKeyPath:@"image"];
         if (photos.count > 0) {
             self_weak_.headImageView.image = photos[0];
             self_weak_.sendImage = photos[0];
         }
    };
    ac.cancelBlock = ^{
       
    };

    [ac showPhotoLibraryWithSender:self];
    
}

#pragma mark - 图片上传
-(void)uploadWithImage:(UIImage*)sendImage{
    NSData *data = UIImageJPEGRepresentation(sendImage,0.5);
    NSInteger timeStamp = [[NSNumber numberWithDouble:
                            [[NSDate date] timeIntervalSince1970]] integerValue];
    NSString *path = NSTemporaryDirectory();
    NSString *fileName = [NSString stringWithFormat: @"%@_%li_avatar.jpeg",self.userModel.userId,timeStamp];
    NSString *urlstr = [NSString stringWithFormat: @"%@/%@",path,fileName];
    NSURL *url = [NSURL fileURLWithPath:urlstr];
    [data writeToURL:url atomically:YES];
    [self.uploadManager setFile:url];
    self.hud = [JPProgressHUD showLoading];
    [self.uploadManager loadData];
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.userInfoManager]){
        NSDictionary *dic = manager.response.content;
        self.userModel = [MineUserModel mj_objectWithKeyValues:dic[@"data"]];
        if(self.userModel.userId){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.userId forKey:@"userId"];
        }
        if(self.userModel.phone){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.phone forKey:@"phone"];
        }
        if(self.userModel.nickname){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.nickname forKey:@"nickname"];
        }
        if(self.userModel.avatar){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.avatar forKey:@"avatar"];
        }
        if(self.userModel.sex){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.sex forKey:@"sex"];
        }
        if(self.userModel.introduction){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.introduction forKey:@"introduction"];
        }
        
        if(self.userModel.goldNumber){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.goldNumber forKey:@"goldNumber"];
        }
        
        if(self.userModel.signCount){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.signCount forKey:@"signCount"];
        }
        
        if(self.userModel.downTime){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.downTime forKey:@"downTime"];
        }
        
        if(self.userModel.downTimeName){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.downTimeName forKey:@"downTimeName"];
        }
        
        if(self.userModel.downTimeCount){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.downTimeCount forKey:@"downTimeCount"];
        }
        
        if(self.userModel.wordNumber){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.wordNumber forKey:@"wordNumber"];
        }
        
        if(self.userModel.mode){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.mode forKey:@"mode"];
        }
        
        if(self.userModel.addGoldNumber){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.addGoldNumber forKey:@"addGoldNumber"];
        }
        
        [self refreshUI];
    }
    
    if([manager isEqual:self.editManager]){
        if(self.hud){
            [self.hud removeFromSuperview];
        }
        if(self.picUrl){
            self.picUrl = nil;
        }
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        self.userModel = [MineUserModel mj_objectWithKeyValues:dic[@"data"]];
        if(self.userModel.userId){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.userId forKey:@"userId"];
        }
        if(self.userModel.phone){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.phone forKey:@"phone"];
        }
        if(self.userModel.nickname){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.nickname forKey:@"nickname"];
        }
        if(self.userModel.avatar){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.avatar forKey:@"avatar"];
        }
        if(self.userModel.sex){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.sex forKey:@"sex"];
        }
        if(self.userModel.introduction){
            [[NSUserDefaults standardUserDefaults]setObject:self.userModel.introduction forKey:@"introduction"];
        }
        [[NSNotificationCenter defaultCenter]postNotificationName:@"updateUserInfo" object:self.userModel];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    if([manager isEqual:self.uploadManager]){
        self.sendImage = nil;
        NSDictionary *dic = manager.response.content;
        self.picUrl = [NSString stringWithFormat:@"%@",dic[@"data"][@"url"]];
        [[NSUserDefaults standardUserDefaults]setObject:self.picUrl forKey:@"avatar"];
        [self save];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.uploadManager]||[manager isEqual:self.editManager]){
        if(self.hud){
            [self.hud removeFromSuperview];
        }
    }
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UITextViewTextDidChangeNotification object:self.textView];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


@end
